package com.ling.fireworks.ui.pages.main

import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.BlendMode
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.tooling.preview.Preview
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import com.ling.fireworks.ui.pages.main.mvi.MainIntent
import com.ling.fireworks.ui.pages.main.mvi.MainViewModel

/**
 * @author Ling
 * @date :2025/9/15 10:26
 */

@Composable
fun MainPage(){
    val vm = viewModel(MainViewModel::class)
    val state = vm.uiState.collectAsStateWithLifecycle()

    Canvas(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.Black)
            .pointerInput(Unit) {
                detectTapGestures { offset ->
                    vm.sendUiIntent(MainIntent.Launch(offset)) //点击屏幕任意位置发送烟花效果
                }
            }
    ) {
        state.value.fireworks.forEach { firework ->
            firework.particles.forEach { particle ->
                if (particle.life > 0) {
                    drawCircle(
                        color = firework.color.copy(alpha = particle.alpha * particle.life),
                        radius = particle.size * particle.life,
                        center = particle.position,
                        blendMode = BlendMode.Plus
                    )

                    // 拖尾效果
                    drawCircle(
                        brush = Brush.radialGradient(
                            colors = listOf(
                                firework.color.copy(alpha = 0.3f * particle.life),
                                Color.Transparent
                            ),
                            radius = particle.size * 2f
                        ),
                        radius = particle.size * 4f,
                        center = particle.position,
                        blendMode = BlendMode.Screen
                    )
                }
            }
        }
    }
}

@Preview
@Composable
fun MainPagePreview(){
    MainPage()
}